package com.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.config.security.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
@Component//记得加入IOC
public class MyBatisPlusFillTime implements MetaObjectHandler {
    //token存放请求头的位置
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    //Bearer
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void insertFill(MetaObject metaObject) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.setFieldValByName("createTime",df.format(new Date()).toString(),metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.setFieldValByName("updateTime",df.format(new Date()).toString(),metaObject);
        System.out.println("MybatisPlus拦截器");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader(tokenHeader);
        if (null == authorization || !authorization.startsWith(tokenHead)) {
            return;
        }
        String token = authorization.substring(tokenHead.length());
        String username = jwtTokenUtil.getUserNameFormToken(token);
        log.info("mybatis拦截器获取到操作人：{}", username);
        this.setFieldValByName("updateBy", username,metaObject);
    }
}
